package com.qiangesoft.blog.system.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import com.qiangesoft.blog.common.result.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import static com.qiangesoft.blog.common.result.ResultCode.*;

/**
 * 异常处理
 *
 * @author qiange
 */
@RestControllerAdvice(basePackages = "com.qiangesoft.blog")
@Slf4j
public class GlobalException {

    /**
     * 校验异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseResult handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder errorMessage = new StringBuilder();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage.append(fieldError.getDefaultMessage()).append(";");
        }
        return ResponseResult.error(PARAM_ERROR.getCode(), errorMessage.toString());
    }

    /**
     * 校验异常
     */
    @ExceptionHandler(value = ValidationException.class)
    public ResponseResult handleValidationException(ValidationException ex) {
        String message = ex.getMessage();
        return ResponseResult.error(PARAM_ERROR.getCode(), message);
    }

    /**
     * 校验异常
     */
    @ExceptionHandler(value = BindException.class)
    public ResponseResult handleBindException(BindException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder errorMessage = new StringBuilder();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage.append(fieldError.getDefaultMessage()).append(";");
        }
        return ResponseResult.error(PARAM_ERROR.getCode(), errorMessage.toString());
    }

    /**
     * 校验异常
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    public ResponseResult handleConstraintViolationException(ConstraintViolationException ex) {
        Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
        Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
        List<String> msgList = new ArrayList<>();
        while (iterator.hasNext()) {
            ConstraintViolation<?> cvl = iterator.next();
            msgList.add(cvl.getMessageTemplate());
        }
        return ResponseResult.error(PARAM_ERROR.getCode(), String.join(",", msgList));
    }

    /**
     * 拦截违法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseResult handleIllegalArgumentException(IllegalArgumentException ex) {
        log.error(" msg : " + ex.getMessage(), ex);
        if (StringUtils.isBlank(ex.getLocalizedMessage())) {
            return ResponseResult.error(ERROR.getCode(), ERROR.getDesc());
        }
        return ResponseResult.error(ex.getMessage());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseResult handleBusinessException(BusinessException ex) {
        if (StringUtils.isBlank(ex.getLocalizedMessage()) || StringUtils.isBlank(ex.getMessage())) {
            return ResponseResult.error(ERROR.getCode(), ERROR.getDesc());
        }
        return ResponseResult.error(ex.getCode(), ex.getMessage());
    }

    /**
     * 拦截未登录异常
     */
    @ExceptionHandler(NotLoginException.class)
    public ResponseResult handleNotLoginException(NotLoginException ex) {
        log.error(" msg : " + ex.getMessage(), ex);
        return ResponseResult.error(NOT_LOGIN.getCode(), NOT_LOGIN.getDesc());
    }

    /**
     * 拦截权限不足异常
     */
    @ExceptionHandler(NotPermissionException.class)
    public ResponseResult handleNotPermissionException(NotPermissionException ex) {
        log.error(" msg : " + ex.getMessage(), ex);
        return ResponseResult.error(NO_PERMISSION.getCode(), "无此权限：" + ex.getCode());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseResult handleRuntimeException(RuntimeException ex) {
        log.error(ex.getMessage(), ex);
        return ResponseResult.error(ERROR_DEFAULT.getCode(), ERROR_DEFAULT.getDesc());
    }

    /**
     * 拦截系统异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseResult handleException(Exception ex) {
        log.error(ex.getMessage(), ex);
        if (StringUtils.isBlank(ex.getLocalizedMessage())) {
            return ResponseResult.error(ERROR.getCode(), ERROR.getDesc());
        }
        return ResponseResult.error(ex.getMessage());
    }

}
